<?php

class ImageHelper {
	
	public static function createRessource($path) {
		
		$extension = file_get_extension($path);
		
		$ressource = null;
		switch($extension) {
			case ".jpeg":
			case ".jpg":
				$ressource = imagecreatefromjpeg($path);
				break;
			case ".png":
				$ressource = imagecreatefrompng($path);
				break;
			case ".gif":
				$ressource = imagecreatefromgif($path);
				break;
		}
		return $ressource;
	}
	public static function createNewRessource($options = array()) {
		$height = $options['height'];
		$width = $options['width'];
		
		$ressource = imagecreatetruecolor($width, $height);
		return $ressource;
		
	}
	
	public static function resize($path, $dest_path, $options = array()) {
		require_once(HELPER_PATH.'file.helper.php');
		
		$img_src = self::createRessource($path);
		$height = $options['height'];
		$width = $options['width'];
		$width_src = imagesx($img_src);
		$height_src = imagesx($img_src);
		
		if (empty($height)) {
			$ratio = $width/$width_src;
			$height = round($height_src*$ratio);
		}
		if (empty($width)) {
			$ratio = $height/$height_src;
			$width = round($width_src*$ratio);
		}
		
		
		$img_dst = self::createNewRessource(array(
			'height' => $height,
			'width' => $width
		));
		$extension = file_get_extension($dest_path);
		if (in_array($extension, array(".png", ".jpeg", ".jpg"))) {
			imagealphablending($img_dst, false);
			imagesavealpha($img_dst,true);
			$transparent = imagecolorallocatealpha($img_dst, 255, 255, 255, 127);
			imagefilledrectangle($img_dst, 0, 0, $width, $height, $transparent);
		}
		imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $width, $height, $width_src, $height_src);
		
		switch($extension) {
			case ".jpeg":
			case ".jpg":
				imagejpeg($img_dst, $dest_path);
				break;
			case ".png":
				imagepng($img_dst, $dest_path);
				break;
			case ".gif":
				imagegif($img_dst, $dest_path);
				break;
		}
	}
	
}